package com.songcha.library_business.helper

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.AdvertHelper.Companion.renderXxlAdView_GDT
import com.songcha.library_business.helper.AdvertHelper.Companion.showRewardAdvert_GDT
import com.songcha.library_business.helper.AdvertHelper.Companion.showRewardVideoAd
import com.songcha.library_business.helper.AdvertHelper.IAdvertRenderListener
import com.songcha.library_business.helper.AdvertHelper.ILoadAdvertCommonListener
import com.songcha.library_business.helper.AdvertHelper.IUnifiedBannerADListenerGDT
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.library_common.util.px2dp
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import java.util.concurrent.TimeUnit

class AdvertCoverHelper {
    companion object{

        @JvmStatic
        @Synchronized
        fun loadAdvertByCover(activity: Activity,type:Int,advertInfo:AdvertInfoBean,adContainer:ViewGroup?,margin: Float,listener: ILoadAdvertCommonListener){

            if(!FunctionConfig.IS_ADVERT_ENABLED || (advertInfo.code_ids.csj.isEmpty() && advertInfo.code_ids.gdt.isEmpty()))
                return

            //TODO
            //AutoSize.autoConvertDensityOfGlobal(activity)

            var loadAdvertDispose: Disposable? = null
            var isLoadAdvertSuccess = false
            var isLoadAdvertError = false
            var isAdvertClose = false
            var isLoadTimeout = false

            fun initLoadTimeout(isInit:Boolean,type:Int,idx:Int,_listener: ILoadAdvertCommonListener){
                if(idx == 0 || isInit){
                    isLoadAdvertSuccess = false
                    isLoadAdvertError = false
                    isLoadTimeout = false
                    isAdvertClose = false

                    val timeout = advertInfo.timeout.toLong()
                    loadAdvertDispose = Observable.intervalRange(0,timeout,0,1, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe{
                            if(it == timeout - 1){
                                if(!isLoadAdvertSuccess && !isLoadAdvertError && !isAdvertClose){
                                    //ToastUtil.show("加载广告超时")
                                    isLoadTimeout = true
                                    _listener.onError(AdvertInfoBean.ADVERT_TYPE_CSJ,-1,"load advert timeout")
                                }

                            }
                        }
                }
            }

            fun loadAdvertByCoverCsj(isInit:Boolean,idx:Int,_listener: ILoadAdvertCommonListener,code:Int = -1,msg:String = "unknow error"){
                if(idx < 0) return
                initLoadTimeout(isInit,AdvertInfoBean.ADVERT_TYPE_CSJ,idx,_listener)

                if(isLoadTimeout) return

                if(idx > advertInfo.code_ids.csj.size - 1 || advertInfo.code_ids.csj[idx].id.isEmpty()) {
                    if(isLoadTimeout) return
                    isLoadAdvertError = true
                    loadAdvertDispose?.dispose()
                    _listener.onError(AdvertInfoBean.ADVERT_TYPE_CSJ,code,msg)
                    return
                }

                fun onError(code:Int,msg:String){
                    if(isLoadTimeout) return
                    loadAdvertByCoverCsj(false,idx + 1,_listener,code,msg)
                }

                fun onSuccess(height:Int,view:View?){
                    if(isLoadTimeout || isLoadAdvertError || isLoadAdvertSuccess) return
                    isLoadAdvertSuccess = true
                    loadAdvertDispose?.dispose()
                    _listener.onSuccess(AdvertInfoBean.ADVERT_TYPE_CSJ,height,view)
                }

                fun onClose(){
                    if(isLoadTimeout) return
                    isAdvertClose = true
                    _listener.onClose(AdvertInfoBean.ADVERT_TYPE_CSJ)
                }

                val item = advertInfo.code_ids.csj[idx]

                if(type == AdvertHelper.ADVERT_TYPE_SPLASH){
                    val advertHeight = if(item.ar > 0f) ScreenUtil.getScreenRealHeight() * item.ar else ScreenUtil.getScreenRealHeight()
                    AdvertHelper.loadSplashAd(activity,item.id,advertHeight.toInt(),
                        VarConfig.ADVERT_SPLASH_INFO.preload,object : AdvertHelper.ICSJSplashAdListener {
                            override fun onSplashLoadSuccess() {

                            }

                            override fun onSplashLoadFail(code: Int, msg: String) {
                                onError(code,msg)
                            }

                            override fun onSplashRenderSuccess() {
                                onSuccess(advertHeight.toInt(),null)
                            }

                            override fun onSplashAdClose() {
                                onClose()
                            }

                            override fun onSplashRenderFail(code: Int, msg: String) {
                                onError(code,msg)
                            }

                        })
                }else if(type == AdvertHelper.ADVERT_TYPE_INSERT_SCREEN){
                    AdvertHelper.loadInsertScreenAdvert(activity,item.id,
                        advertInfo.preload,object :AdvertHelper.IInsertScreenAdListener{
                            override fun onError(code: Int, msg: String) {
                                onError(code,msg)
                            }

                            override fun onSuccess() {
                                onSuccess(item.ar.toInt(),null)
                            }

                            override fun onAdShow() {

                            }

                            override fun onAdClose() {
                                onClose()
                            }

                        })
                }else if(type == AdvertHelper.ADVERT_TYPE_REWARD){
                    AdvertHelper.loadRewardAdvert(activity,item.id,advertInfo.preload,object :AdvertHelper.IRewardVideoAdListener{
                        override fun onError(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onVideoError() {
                            onError(-1,"videoError")
                        }

                        override fun onRewardArrived(
                            isRewardValid: Boolean,
                            rewardType: Int,
                            bundle: Bundle?
                        ) {
                            onSuccess(0,null)
                        }

                        override fun onRewardVideoCached() {
                            if(isLoadTimeout || isLoadAdvertError || isLoadAdvertSuccess) return
                            showRewardVideoAd(activity)
                        }

                        override fun onClose() {
                            onClose()
                        }

                    })
                }else if(type == AdvertHelper.ADVERT_TYPE_BANNER){
                    val initDensity = AutoSizeConfig.getInstance().initDensity
                    val adWidth = (ScreenUtil.getScreenWidth() - margin.dp2px()) / initDensity
                    val adHeight = if(item.ar > 0f) adWidth / item.ar else 0f

                    AdvertHelper.loadBannerAdvert(activity,item.id,adWidth,adHeight,advertInfo.preload,object :AdvertHelper.INativeExpressAdListener{
                        override fun onError(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onNativeExpressAdLoad(adViews: List<Any>) {
                            AdvertHelper.renderBannerAdvert_CSJ(activity,adViews[0],object :
                                IAdvertRenderListener {
                                override fun onAdClicked(view: View, p1: Int) {

                                }

                                override fun onAdShow(view: View, p1: Int) {

                                }

                                override fun onRenderFail(p0: View, p1: String, p2: Int) {
                                    onError(p2,p1)
                                }

                                override fun onRenderSuccess(view: View, p1: Float, p2: Float) {
                                    onSuccess(adHeight.toInt(),view)
                                }

                                override fun onDislikeReasonSelected(
                                    position: Int,
                                    value: String,
                                    enforce: Boolean
                                ) {
                                    onClose()
                                }

                            })
                        }

                    })
                }else if(type == AdvertHelper.ADVERT_TYPE_XXL){
                    val initDensity = AutoSizeConfig.getInstance().initDensity
                    val adWidth = (ScreenUtil.getScreenWidth() - margin.dp2px()) / initDensity

                    AdvertHelper.loadXxlAdvert(activity,item.id,adWidth,0f,1,advertInfo.preload,object :AdvertHelper.INativeExpressAdListener{
                        override fun onError(code: Int, msg: String) {
                            //LogUtil.log("loadXxlAdvert onError",type,item.id,code,msg)
                            onError(code,msg)
                        }

                        override fun onNativeExpressAdLoad(adViews: List<Any>) {
                            if(isLoadTimeout || isLoadAdvertError || isLoadAdvertSuccess) return

                            AdvertHelper.renderXxlAdView_CSJ(activity,adViews[0],object :IAdvertRenderListener{
                                override fun onAdClicked(view: View, p1: Int) {

                                }

                                override fun onAdShow(view: View, p1: Int) {

                                }

                                override fun onRenderFail(p0: View, p1: String, p2: Int) {
                                    onError(p2,p1)
                                }

                                override fun onRenderSuccess(view: View, p1: Float, p2: Float) {
                                    onSuccess(0,view)
                                }

                                override fun onDislikeReasonSelected(
                                    position: Int,
                                    value: String,
                                    enforce: Boolean
                                ) {
                                    onClose()
                                }

                            })
                        }

                    })
                }

            }

            fun loadAdvertByCoverGdt(isInit:Boolean,idx:Int,_listener: ILoadAdvertCommonListener,code:Int = -1,msg:String = "unknow error"){
                if(idx < 0) return

                initLoadTimeout(isInit,AdvertInfoBean.ADVERT_TYPE_GDT, idx,_listener)

                if(isLoadTimeout) return

                if(idx > advertInfo.code_ids.gdt.size - 1 || advertInfo.code_ids.gdt[idx].id.isEmpty()) {
                    if(isLoadTimeout) return
                    isLoadAdvertError = true
                    loadAdvertDispose?.dispose()
                    _listener.onError(AdvertInfoBean.ADVERT_TYPE_GDT,code,msg)
                    return
                }

                fun onError(code:Int,msg:String){
                    if(isLoadTimeout) return
                    loadAdvertByCoverGdt(false,idx + 1,_listener,code,msg)
                }

                fun onSuccess(height:Int,view:View?){
                    if(isLoadTimeout || isLoadAdvertError || isLoadAdvertSuccess) return
                    isLoadAdvertSuccess = true
                    loadAdvertDispose?.dispose()
                    _listener.onSuccess(AdvertInfoBean.ADVERT_TYPE_GDT,height,view)
                }

                fun onClose(){
                    if(isLoadTimeout) return
                    isAdvertClose = true
                    _listener.onClose(AdvertInfoBean.ADVERT_TYPE_GDT)
                }

                val item = advertInfo.code_ids.gdt[idx]

                if(type == AdvertHelper.ADVERT_TYPE_SPLASH){
                    val advertHeight = if(item.ar > 0f) ScreenUtil.getScreenRealHeight() * item.ar else ScreenUtil.getScreenRealHeight()
                    AdvertHelper.loadSplashAd_GDT(activity,item.id,object : AdvertHelper.ISplashADListenerGDT {
                        override fun onSplashRenderFail(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onADDismissed() {
                            onClose()
                        }

                        override fun onNoAD(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onADPresent() {

                        }

                        override fun onADClicked() {

                        }

                        override fun onADTick(p0: Long) {

                        }

                        override fun onADExposure() {

                        }

                        override fun onADLoaded(p0: Long) {
                            onSuccess(advertHeight.toInt(),null)
                        }

                    })

                }else if(type == AdvertHelper.ADVERT_TYPE_INSERT_SCREEN){
                    AdvertHelper.loadInsertScreenAdvert_GDT(activity,item.id,item.ar > 0f,object :AdvertHelper.IInsertScreenAdListener{
                        override fun onError(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onSuccess() {
                            onSuccess(item.ar.toInt(),null)
                        }

                        override fun onAdShow() {

                        }

                        override fun onAdClose() {
                            onClose()
                        }

                    })
                }else if(type == AdvertHelper.ADVERT_TYPE_REWARD){
                    AdvertHelper.loadRewardAdvert_GDT(activity,item.id,object:AdvertHelper.IRewardVideoADListenerGDT{
                        override fun onADLoad() {
                            if(isLoadTimeout || isLoadAdvertError || isLoadAdvertSuccess) return
                            showRewardAdvert_GDT()
                        }

                        override fun onVideoCached() {

                        }

                        override fun onADShow() {

                        }

                        override fun onADExpose() {

                        }

                        override fun onReward(p0: MutableMap<String, Any>) {
                            onSuccess(0,null)
                        }

                        override fun onADClick() {

                        }

                        override fun onVideoComplete() {

                        }

                        override fun onADClose() {
                            onClose()
                        }

                        override fun onError(code: Int, msg: String) {
                            onError(code,msg)
                        }

                    })
                }else if(type == AdvertHelper.ADVERT_TYPE_BANNER){
                    val adWidth = (ScreenUtil.getScreenWidth() - margin.dp2px())
                    val adHeight = if(item.ar > 0f) adWidth / item.ar else 0f
                    if(adContainer == null){
                        onError(-1,"gdt banner ad container view cannot be null")
                    }

                    AdvertHelper.loadBannerAdvert_GDT(activity,item.id,adContainer!!,adWidth,adHeight,object:
                        IUnifiedBannerADListenerGDT {
                        override fun onError(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onNoAD(code: Int, msg: String) {
                            onError(code,msg)
                        }

                        override fun onADReceive() {
                            onSuccess(adHeight.toInt(),null)
                        }

                        override fun onADExposure() {

                        }

                        override fun onADClosed() {
                            onClose()
                        }

                        override fun onADClicked() {

                        }

                        override fun onADLeftApplication() {

                        }

                    })
                }else if(type == AdvertHelper.ADVERT_TYPE_XXL){
                    val initDensity = AutoSizeConfig.getInstance().initDensity
                    val density = ScreenUtil.getDensity()
                    val scale = density / initDensity
                    //val adWidth = ((360 - margin) * scale).toInt()
                    val adWidth = ((ScreenUtil.getScreenWidth() - margin.dp2px()) * scale).px2dp().toInt()

                    AdvertHelper.loadXxlAdvert_GDT(activity,item.id,adWidth,1,object :AdvertHelper.IGDTNativeExpressADListener{
                        override fun onNoAD(code: Int, msg: String) {
                            //LogUtil.log("loadXxlAdvert onError",type,item.id,code,msg)
                            onError(code,msg)
                        }

                        override fun onADLoaded(adViews: List<View>) {
                            LogUtil.log("aaa4",isLoadTimeout,isLoadAdvertError,isLoadAdvertSuccess)
                            if(isLoadTimeout || isLoadAdvertError || isLoadAdvertSuccess) return
                            renderXxlAdView_GDT(adViews[0])
                        }

                        override fun onRenderFail(adView: View) {
                            onError(-1,"onRenderFail")
                        }

                        override fun onRenderSuccess(adView: View) {
                            onSuccess(0,adView)
                        }

                        override fun onADExposure(adView: View) {

                        }

                        override fun onADClicked(adView: View) {

                        }

                        override fun onADClosed(adView: View) {
                            onClose()
                        }

                        override fun onADLeftApplication(adView: View) {

                        }

                    })
                }

            }

            if(advertInfo.type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                loadAdvertByCoverCsj(true,0,object : ILoadAdvertCommonListener {
                    override fun onSuccess(type: Int, height: Int,view: View?) {
                        listener.onSuccess(type,height,view)
                    }

                    override fun onError(type: Int,code:Int,msg:String) {
                        loadAdvertByCoverGdt(true,advertInfo.code_ids.gdt.size - 1,object : ILoadAdvertCommonListener {
                            override fun onSuccess(type: Int, height: Int,view: View?) {
                                listener.onSuccess(type,height,view)
                            }

                            override fun onError(type: Int,code:Int,msg:String) {
                                listener.onError(type,code,msg)
                            }

                            override fun onClose(type: Int) {
                                listener.onClose(type)
                            }

                        })
                    }

                    override fun onClose(type: Int) {
                        listener.onClose(type)
                    }

                })

            }else if(advertInfo.type == AdvertInfoBean.ADVERT_TYPE_GDT){
                loadAdvertByCoverGdt(true,0,object : ILoadAdvertCommonListener {
                    override fun onSuccess(type: Int, height: Int,view: View?) {
                        listener.onSuccess(type,height,view)
                    }

                    override fun onError(type: Int,code:Int,msg:String) {
                        loadAdvertByCoverCsj(true,advertInfo.code_ids.csj.size - 1,object : ILoadAdvertCommonListener {
                            override fun onSuccess(type: Int, height: Int,view: View?) {
                                listener.onSuccess(type,height,view)
                            }

                            override fun onError(type: Int,code:Int,msg:String) {
                                listener.onError(type,code,msg)
                            }

                            override fun onClose(type: Int) {
                                listener.onClose(type)
                            }

                        })
                    }

                    override fun onClose(type: Int) {
                        listener.onClose(type)
                    }


                })
            }
        }

        @JvmStatic
        fun loadAdvertByCoverBanner(activity: Activity,advertInfo:AdvertInfoBean,adContainer:ViewGroup?,margin: Float){
            loadAdvertByCover(activity,AdvertHelper.ADVERT_TYPE_BANNER,advertInfo,
                adContainer,margin,object:ILoadAdvertCommonListener{
                    override fun onSuccess(type: Int, height: Int, view: View?) {
                        ViewHelper.setVisibility(true,adContainer)
                        if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                            adContainer?.removeAllViews()
                            adContainer?.addView(view)
                        }else if(type == AdvertInfoBean.ADVERT_TYPE_GDT){

                        }
                    }

                    override fun onError(type: Int, code: Int, msg: String) {
                        ViewHelper.setVisibility(false,adContainer)
                        adContainer?.removeAllViews()
                    }

                    override fun onClose(type: Int) {
                        ViewHelper.setVisibility(false,adContainer)
                        adContainer?.removeAllViews()
                    }

                })
        }

        @JvmStatic
        fun loadAdvertByCoverXxl(activity: Activity,advertInfo:AdvertInfoBean,adContainer:ViewGroup?,margin: Float){
            loadAdvertByCover(activity,AdvertHelper.ADVERT_TYPE_XXL,advertInfo,
                adContainer,20f,object:ILoadAdvertCommonListener{
                    override fun onSuccess(type: Int, height: Int, view: View?) {
                        ViewHelper.setVisibility(true,adContainer)
                        adContainer?.removeAllViews()
                        adContainer?.addView(view)
                    }

                    override fun onError(type: Int, code: Int, msg: String) {
                        ViewHelper.setVisibility(false,adContainer)
                        adContainer?.removeAllViews()
                    }

                    override fun onClose(type: Int) {
                        ViewHelper.setVisibility(false,adContainer)
                        adContainer?.removeAllViews()
                    }

                })
        }

    }

}